import { constructProxy } from './proxy'


/**
 * 给MiniVue类原型添加_init方法
 * @param {MiniVue} MiniVue 
 */
export function mixinInit(MiniVue) {
    MiniVue.prototype._init = function (options) {
        init.call(this, options)
    }
}

/**
 * 实现init方法
 * @param {Object} options 
 */
function init(options) {
    this.uid = this.uid ? 1 : (this.uid + 1);
    this._isMiniVue = true; 
    // 初始化beforeCreate 
    this._beforeCreate = options?.beforeCreate?.bind(this)
    // 执行beforeCreate methods和data都未配置
    this._beforeCreate?.()
    // 初始化created
    this._created = options?.created?.bind(this)
    // 初始化beforeMount
    this._beforeMount = options?.beforeMount?.bind(this)
    // 初始化mount
    this._mounted = options?.mounted?.bind(this)
    // 初始化data
    this._data = options?.data ? constructProxy(this, options.data, "") : {}
    // 初始化computed
    // 初始化methods
    options?.methods ? Object.entries(options.methods).forEach(([key, method]) => {
        this[key] = method.bind(this)
    }) : {}
    // 事件注册和数据观测完成执行created钩子
    this._created?.()
    // 挂载dom
    if(options?.el) {
        // 收集依赖，渲染虚拟dom
        this.$mount(options.el).then(()=> {
            // 虚拟dom构建完成，执行beforeMount
            this._beforeMount?.()
        })
        this.$render().then(()=> {
            // 虚拟dom构建完成，执行beforeMount
            this._mounted?.()
        })
    }
}